import re

from django.http import HttpResponse
from django.shortcuts import render,reverse

class AdminLoginMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        # 检测用户是否登陆
        user = request.session['AdminUser']
        if not user :
            # 访问后台除登陆页面外的其他页面时，需要先登陆
            loginurl = [
                        reverse('myadmin_login'),
                        reverse('myadmin_verifycode')
                        ]
            if re.search('admin',request.path) and request.path not in loginurl :
                return HttpResponse('<script>alert("需要先登录");location.href="/admin/login"</script>')

        response = self.get_response(request)
        # Code to be executed for each request/response after
        # the view is called.
        return response